package com.zhima.task;

import cn.hutool.core.lang.UUID;
import com.zhima.panel.RandomInDataConfiguration;
import com.zhima.util.FileUtil;

import javax.swing.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import static cn.hutool.core.io.FileUtil.del;
import static com.zhima.frame.MainFrame.DEFAULT_BASE_DIR;
import static com.zhima.util.FileUtil.ensureDirExist;

public class PreviewInDataSupplier implements Supplier<String> {
    private final List<RandomInDataConfiguration> randomInDataConfigurations;
    private final ExecutorService executorService = Executors.newFixedThreadPool(1);

    public PreviewInDataSupplier(List<RandomInDataConfiguration> randomInDataConfigurations) {
        this.randomInDataConfigurations = randomInDataConfigurations;
    }

    @Override
    public String get() {
        String tempFileDirPath = String.format("%s\\%s", DEFAULT_BASE_DIR, UUID.fastUUID().toString(true));
        String tempFilePath = String.format("%s\\test1.in", tempFileDirPath);
        ensureDirExist(tempFileDirPath);
        new GenerateInDataTask(executorService, randomInDataConfigurations, new JLabel(tempFileDirPath), 1).run();
        List<String> results = null;
        try {
            results = FileUtil.readFile(tempFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder ans = new StringBuilder();
        if (results == null) {
            return "";
        }
        for (String result : results) {
            ans.append(result);
            ans.append("\n");
        }
        del(tempFileDirPath);
        return ans.toString();
    }
}
